Published on January 17, 2025

返回

转到题目

思路

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
unordered_map<int, int> p;

int find(int x) {
    if(p.find(x)==p.end()) p[x] =x;
	if (x != p[x]) {
		p[x] = find(p[x]);
	}
	return p[x];
}
void merge(int x, int y) {
	int rootX = find(x);
	int rootY = find(y);
	p[rootX] = rootY;
}
int n, m;
int main() {
	cin >> n >> m;
	vector<int> f(n + 1);
	for (int i = 1; i <= n; i++) {
		cin >> f[i];
	}
	unordered_map<int, unordered_map<int, int>>tc;
	int x, y;
	for (int i = 0; i < m; i++) {
		cin >> x >> y;
		merge(x, y);
	}
	for (int i = 1; i <= n; i++) {
		int root = find(i);
		if (p.find(i) != p.end())tc[root][f[i]]++;
	}
	int res = 0;
	for (auto ma : tc) {
		int tmax = 0;
		int total = 0;
		for (auto e : ma.second) {
			tmax = max(tmax, e.second);
			total += e.second;
		}
		res += (total - tmax);
	}
	cout << res << endl;
	return 0;
}